﻿using LP;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AddressableAssets;

namespace Launch
{
    public class AssetBundleUpdateMgr : AbsMgr
    {
        public override void OnInit()
        {
            base.OnInit();
            Global.CoroutineMgrIns.StartCoroutine(CheckAB(), TokenSource.Token);
        }

        private IEnumerator CheckAB()
        {
            //初始化Addressable系统
            yield return Addressables.InitializeAsync();
            //检查出需要更新的列表
            var checkHandle = Addressables.CheckForCatalogUpdates();
            List<string> updateCatalogIds = new List<string>();
            checkHandle.Completed += (re) => { updateCatalogIds.AddRange(re.Result); };
            yield return checkHandle;
            if (updateCatalogIds.Count > 0)
            {
                //要下载的AB包
                List<object> updateAbNames = new List<object>();
                var updateHandle = Addressables.UpdateCatalogs(updateCatalogIds, false);
                updateHandle.Completed += (re) =>
                {
                    foreach (var item in re.Result)
                    {
                        updateAbNames.AddRange(item.Keys);
                    }
                };
                yield return updateHandle;

                // 清楚下载缓存
                yield return Addressables.ClearDependencyCacheAsync(updateAbNames as IEnumerable, true);

                //获取要下载AB的字节数
                var downloadHandle = Addressables.GetDownloadSizeAsync(updateAbNames as IEnumerable);
                yield return downloadHandle;
                //是否需要更新资源
                bool isUpdateAsset = downloadHandle.Result > 0;
                if (isUpdateAsset)
                {
                    string str = $"正在为您更新资源,资源大小:\t{(downloadHandle.Result).ToString("F2")}B";
                    // string str = $"正在为您更新资源,资源大小:\t{(downloadHandle.Result / (1024 * 1024)).ToString("F2")}MB";
                    Global.UIEventHandler.Notify(ELaunch.OnUpdateLoadingHintText, ValueTuple.Create(str));

                    //下载AB
                    var downloadDependenceHandle =
                        Addressables.DownloadDependenciesAsync(updateAbNames as IEnumerable,
                            Addressables.MergeMode.Union);
                    while (!downloadDependenceHandle.IsDone)
                    {
                        float progress = downloadDependenceHandle.PercentComplete * 0.8f;
                        Debug.Log($"资源下载进度：{progress}");
                        Global.UIEventHandler.Notify(ELaunch.OnUpdateLoadingProgress, ValueTuple.Create(progress));
                        yield return null;
                    }

                    Debug.Log("资源下载进度：0.8");
                    Global.UIEventHandler.Notify(ELaunch.OnUpdateLoadingProgress, ValueTuple.Create(0.8f));
                    //等待0.5秒关闭资源更新进度条
                    yield return new WaitForSeconds(0.5f);
                    Addressables.Release(downloadDependenceHandle);
                }

                Addressables.Release(downloadHandle);
                Addressables.Release(updateHandle);
            }
            else
            {
                Debug.Log("未检测出需要更新的资源");
                Global.UIEventHandler.Notify(ELaunch.OnUpdateLoadingProgress, ValueTuple.Create(0.8f));
            }

            Global.SysEventHandler.Notify(ESys.LoadGameConfigs);
        }
    }
}